import PWSApp from "../../core/app";
import { Promise } from 'es6-promise';
import { Request , Response } from "express";

import { ObjectID } from "mongodb";
import HomeBaseAction from "./act.base";
import * as utils from "../../core/utils";
import { Magics } from "../../core/magics";
import UserModel from "../../models/mod.user";
import { MongoColls } from "../../config/mongo";
import { ErrCode } from "../../core/error.code";
import ShopModel, { Shop } from "../../models/mod.shop";
import {
    RouteType,
} from "../../core/defines";

export default class ShopAction extends HomeBaseAction {
    private _shopMod : ShopModel;
    private _userMod : UserModel;

    constructor( app : PWSApp ) {
        super( app );
        this._shopMod = new ShopModel( this.db.collection( MongoColls.SHOP ) );
        this._userMod = new UserModel( this.db.collection( MongoColls.USER ) );
    }

    name() { return `${this.app.name}ShopAction`; }

    protected _setRoutes() {
        this._setRoot('/shop');
        this._route( RouteType.GET , '/shop/:sid' , this._actShop );
    }

    private _actShop( req : Request , res : Response ) {
        let shop : Object;
        Promise.resolve().then( () => {
            let { sid } = req.params;
            if( !sid ) {
                return Promise.reject({err_code: ErrCode.ArgsInvalid});
            }
            sid = sid.toLowerCase();
            return this._shopMod.checkExist({sid});
        }).then((shop: Shop) => {
            if(!shop){
                return Promise.reject({err_code: ErrCode.ShopNotFound});
            }
            let result = {
                shop ,
                user       : req.session[ Magics.SessUser ] ,
                err_code   : ErrCode.Success
            };
            res.render( 'home/shop.html' , result );
        }).catch( ( err ) => {
            this._errHandler( req , res , err );
        } );
    }
}